package com.xudow.app.dynamicstate_old.module.message;

import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.jude.beam.expansion.BeamBaseActivity;
import com.xudow.app.R;
import com.xudow.app.dynamicstate_old.data.RongYunModel;
import com.xudow.app.util.StringUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.message.LocationMessage;

/**
 * Created by ske on 2016/7/13.
 */
public class LocationActivity extends BeamBaseActivity {
    @BindView(R.id.map_view)
    MapView mMapView;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.ok)
    Button ok;

    LocationClient mLocClient;
    public MyLocationListener myListener;

    BaiduMap baiduMap;
    BitmapDescriptor bd = BitmapDescriptorFactory.fromResource(R.drawable.umeng_socialize_location_on);
    private LocationMessage locationMessage;
    String strAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        ButterKnife.bind(this);
        baiduMap = mMapView.getMap();
        locationMessage = getIntent().getParcelableExtra("location");
        if (locationMessage != null) {
            ok.setVisibility(View.GONE);
            LatLng ll = new LatLng(locationMessage.getLat(), locationMessage.getLng());
            MarkerOptions options = new MarkerOptions().position(ll);
            options.icon(bd);
            marker = (Marker) baiduMap.addOverlay(options);
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            address.setText(locationMessage.getPoi());
        } else {
            initListener();
        }
    }

    Marker marker;
    GeoCoder geoCoder;

    private void initListener() {
        myListener = new MyLocationListener();
        baiduMap.setMyLocationEnabled(true);
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(0);
        mLocClient.setLocOption(option);
        mLocClient.start();

        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                baiduMap.clear();
                MarkerOptions options = new MarkerOptions().position(mapPoi.getPosition());
                options.icon(bd);
                marker = (Marker) baiduMap.addOverlay(options);
                address.setText(mapPoi.getName());
                strAddress = mapPoi.getName();
                setLocation();
                return false;
            }
        });
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                baiduMap.clear();
                MarkerOptions options = new MarkerOptions().position(reverseGeoCodeResult.getLocation());
                options.icon(bd);
                marker = (Marker) baiduMap.addOverlay(options);
                address.setText(reverseGeoCodeResult.getAddress());
                strAddress = reverseGeoCodeResult.getAddress();
                setLocation();
            }
        });
        ok.setOnClickListener(v -> {
            if (RongYunModel.getInstance().getLastLocationCallback() != null && locationMessage != null && !StringUtils.isEmpty(strAddress)) {
                RongYunModel.getInstance().getLastLocationCallback().onSuccess(locationMessage);
                RongYunModel.getInstance().setLastLocationCallback(null);
            }
            finish();
        });
    }

    private void setLocation() {
        Uri uri = Uri.parse("http://api.map.baidu.com/staticimage/v2").buildUpon()
                .appendQueryParameter("center", marker.getPosition().latitude + "," + marker.getPosition().longitude)
                .appendQueryParameter("mcode", "666666")
                .appendQueryParameter("ak", "3b40be364cc8abd06fb93b5194070f8e")
                .build();
        locationMessage = LocationMessage.obtain(marker.getPosition().latitude, marker.getPosition().longitude, strAddress, uri);
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        if (mLocClient != null)
            mLocClient.stop();
        // 关闭定位图层
        baiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(location.getDirection())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            baiduMap.setMyLocationData(locData);
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
        }
    }

    @OnClick(R.id.btn_back)
    void cancel(View view) {
        finish();
    }
}
